package com.ruoyi.project.business.domain.rules.daily;

import com.ruoyi.project.business.domain.entity.DailyScheduleEmp;
import com.ruoyi.project.business.domain.entity.Emp;
import com.ruoyi.project.business.domain.model.JudgeResult;
import com.ruoyi.project.business.domain.model.Solution;
import com.ruoyi.project.business.domain.model.daily.DailyScheduleSolution;
import com.ruoyi.project.business.domain.model.daily.TimePeriodMirror;
import com.ruoyi.project.business.domain.rules.ForManagerRule;
import com.ruoyi.project.business.domain.rules.Rule;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 每天总人数
 */
@Data
public class EmpAssignTimeNotRepeat extends ForManagerRule {

    @Override
    public JudgeResult judge(Solution solution, Emp emp) {
        DailyScheduleEmp dailyScheduleEmp = (DailyScheduleEmp) emp;
        TimePeriodMirror tryAssignTimePeriod = dailyScheduleEmp.getTryAssignTimePeriod();
//        List<TimePeriodMirror> dailyShifts = dailyScheduleEmp.getDailyShifts();
        DailyScheduleSolution dailyScheduleSolution = (DailyScheduleSolution) solution;
        List<TimePeriodMirror> userShifts = dailyScheduleSolution.getUserShifts().get(emp.getUserId());

        boolean repeat = isRepeatTimePeriod(userShifts, tryAssignTimePeriod);
        if(! repeat) {
            // 如果未重复就接受
            return accept();
        } else {
            JudgeResult res = null;
            if (getBreakIfReject()) {
                res = stopTask();
            } else {
                res = acceptAndReturn();
            }
            res.setTips("emp EmpAssignTimeNotRepeat 时段存在重复 " + tryAssignTimePeriod.getSegmentStart().toString() + " ~ " + tryAssignTimePeriod.getSegmentEnd().toString() + " 已存在排班");
            return res;
        }
    }

    private static boolean isRepeatTimePeriod(List<TimePeriodMirror> dailyShifts, TimePeriodMirror tryAssignTimePeriod) {
        if(CollectionUtils.isNotEmpty(dailyShifts)) {
            for (TimePeriodMirror timePeriod : dailyShifts) {
                if(timePeriod != null) {
                    if(timePeriod.getSegmentStart().equals(tryAssignTimePeriod.getSegmentStart()) && timePeriod.getSegmentEnd().equals(tryAssignTimePeriod.getSegmentEnd())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void setConflicts() {
        setType(Rule.RULE_TYPE_MANAGER);
        this.conflicts = new ArrayList<>();
    }
}
